package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author stone
 * @description 针对表【wm_user(自媒体用户信息表)】的数据库操作Service实现
 * @createDate 2023-02-27 20:36:07
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser>
        implements WmUserService {

    @Override
    public ResponseResult login(WmUserDTO dto) {
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "用户名和密码都不能为空");
        }

        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (Objects.isNull(wmUser)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
        }

        String inputPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());

        if (!wmUser.getPassword().equals(inputPassword)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        // 登录校验通过，颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(wmUser, wmUserVO);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", wmUserVO);

        return ResponseResult.okResult(map);
    }
}




